package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDto;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService dishService;
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/page")
    public R<IPage<SetmealDto>> page(Integer page, Integer pageSize,String name){
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Setmeal::getName,name);
        IPage<Setmeal> page1=new Page<>(page,pageSize);
        IPage<Setmeal> page2 = setmealService.page(page1,lqw);
        IPage<SetmealDto> page3=new Page<>();
        BeanUtils.copyProperties(page2,page3,"records");
        List<Setmeal> records = page2.getRecords();
        List<SetmealDto> list=  records.stream().map((item)->{
            SetmealDto setmealDto=new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            Long id= item.getCategoryId();
            Category byId = categoryService.getById(id);
            if(byId!=null){
                String name1 = byId.getName();
                setmealDto.setCategoryName(name1);
            }
        return setmealDto;

        }).collect(Collectors.toList());
        page3.setRecords(list);
        return R.success(page3);
    }
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        Integer integer = setmealService.saveWithDish(setmealDto);
        if (integer>0){
            return R.success("保存成功");
        }else{
            return R.error("保存失败");
        }
    }
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }

}
